package com.thx.role.action;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.web.ActionResult;
import com.thx.common.web.WebConstant;
import com.thx.log.LogUtil;
import com.thx.org.model.Company;
import com.thx.org.model.Department;
import com.thx.org.service.CompanyManager;
import com.thx.org.service.DepartmentManager;
import com.thx.role.model.Role;
import com.thx.role.service.RoleManager;
import com.thx.user.model.User;
import com.thx.user.service.UserManager;
import com.thx.user.util.ModuleConstant;

@Namespace("/user")
@Action(value = "role", results = {
		@Result(name = "input", location = "/pages/system/role/input.jsp"),
		@Result(name = "list", location = "/pages/system/role/list.jsp"),
		@Result(name = "view", location = "/pages/system/role/detail.jsp"),
		@Result(name = "selectUsers", location = "/pages/system/role/selectUser.jsp"),
		@Result(name = "selectComUsers", location = "/pages/system/role/selectComUser.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" }),
		@Result(name = "usersJson", type = "json", params = { "root", "users" }) })
@Controller
@Scope("prototype")
public class RoleAction extends CurdAction<Role> {

	private static final long serialVersionUID = 1L;

	@Autowired
	protected RoleManager roleMgr;

	protected String treeNodes;
	protected String userRealName;
	protected List<String> userIds;
	protected List<User> users;
	protected List<User> selectedUsers;

	@Autowired
	protected DepartmentManager departmentMgr;

	@Autowired
	protected CompanyManager companyMgr;

	@Autowired
	protected UserManager userMgr;

	public RoleAction() {
	}

	protected void doList() throws Exception {
		list = roleMgr.searchRole(entity.getRoleName());
	}

	protected void doSave() throws Exception {
		try {
			if (StringUtils.isBlank(id)) {
				entity.setRoleName(StringUtils.strip(entity.getRoleName()));
				entity.setRoleCode(StringUtils.strip(entity.getRoleCode()));
				entity.setDescription(StringUtils.strip(entity.getDescription()));
				entity.setStatus("1");
				entity.setRoleType("0");
				entity.setCreateDate(new Date());
				entity.setComId(AppContext.getCurrentComId());
				roleMgr.save(entity);
				setResult(ActionResult.SUCCESS, "添加成功！");
				LogUtil.log(ModuleConstant.ROLE_MANAGER, LogUtil.ACTION_ADD, LogUtil.RESULT_SUCCESS, "新增角色");
			} else {
				Role role = roleMgr.get(id);
				role.setRoleName(StringUtils.strip(entity.getRoleName()));
				role.setRoleCode(StringUtils.strip(entity.getRoleCode()));
				role.setDescription(StringUtils.strip(entity.getDescription()));
				roleMgr.save(role);
				setResult(ActionResult.SUCCESS, "修改成功！");
				LogUtil.log(ModuleConstant.ROLE_MANAGER, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改角色");
			}
		} catch (Exception e) {
			if (StringUtils.isBlank(id)) {
				setResult(ActionResult.FAIL, "添加失败！");
			} else {
				setResult(ActionResult.FAIL, "修改失败！");
			}
			logger.error(e.getMessage(), e);
		}
	}

	protected void doView() throws Exception {
		if (StringUtils.isNotBlank(id)) {
			entity = roleMgr.get(id);
			if (entity == null) {
				setResult(ActionResult.FAIL, "要查看的记录不存在！！！");
			}
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}

	protected void doDelete() throws Exception {
		if (StringUtils.isNotBlank(id)) {
			roleMgr.delete(id);
			setResult(ActionResult.SUCCESS, "删除成功！！！");
			LogUtil.log(ModuleConstant.ROLE_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除角色");
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}

	protected void doDelMulti() throws Exception {
		if (delId != null && delId.length > 0) {
			delId = delId[0].split(",");
			roleMgr.delMulti(delId);
			setResult(ActionResult.SUCCESS, "删除成功！！！");
			LogUtil.log(ModuleConstant.ROLE_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除角色");
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}

	public String setDelStatus() {
		if (delId != null && delId.length > 0) {
			delId = delId[0].split(",");
			roleMgr.delStatus(delId);
			setResult(ActionResult.SUCCESS, "删除成功！！！");
			LogUtil.log(ModuleConstant.ROLE_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除角色");
		} else {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
		return JSON;
	}

	protected void doInput() throws Exception {
		if (StringUtils.isNotBlank(id)) {
			entity = roleMgr.get(id);
			if (entity == null) {
				setResult(ActionResult.FAIL, "要修改的记录不存在！！！");
			}
		}
	}

	/**
	 * 验证角色名是否存在
	 */
	public void checkRoleName() {
		try {
			Role role = roleMgr.findByName(entity.getRoleName());
			if (role == null) {
				writeJson("true");
			} else {
				if (StringUtils.isNotBlank(id) && id.equals(role.getRoleId())) {
					// --修改时用户名和原来的可以保持一致
					writeJson("true");
				} else {
					writeJson("false");
				}

			}

		} catch (Exception e) {
			setResult(ActionResult.FAIL, "服务器异常！");
		}
	}

	public String toSelectUsers() {
		String style = AppContext
				.getProperties(WebConstant.ROLE_SELECT_USER_KEY);
		if (StringUtils.isBlank(style)
				|| (!"org".equals(StringUtils.strip(style)) && !"all"
						.equals(StringUtils.strip(style)))) {
			style = "org";
		}
		if ("org".equals(StringUtils.strip(style))) {
			return selectOrgUsers();
		} else if ("all".equals(StringUtils.strip(style))) {
			return selectAllUsers();
		}
		return null;
	}

	protected String selectOrgUsers() {
		Role role = roleMgr.get(id);
		if (role != null) {
			Set<User> us = role.getUsers();
			if (us != null && us.size() > 0) {
				Iterator<User> it = us.iterator();
				userIds = new ArrayList<String>();
				while (it.hasNext()) {
					userIds.add(it.next().getUserId());
				}
			}

			String comId = AppContext.getCurrentComId();
			Company company = companyMgr.get(comId);
			Department root = new Department();
			root.setDepId(comId);
			root.setDepName(company.getComName());
			root.setFullName(company.getComName());
			// --获得该企业的一级部门
			List<Department> depts = departmentMgr.getByParentId(null);
			List<User> users = userMgr.findByDeptId(null);
			if (users != null && users.size() > 0) {
				root.setUsers(new HashSet(users));
			}
			root.setChildren(depts);
			for (Department d : depts) {
				getChildrenDepAndUsers(d);
			}
			Option op = getOptions(root);
			treeNodes = com.alibaba.fastjson.JSON.toJSONString(op);
		}
		return "selectUsers";
	}

	protected String selectAllUsers() {
		Role role = roleMgr.get(id);
		if (role != null) {
			Set<User> us = role.getUsers();
			if (us != null && us.size() > 0) {
				Iterator<User> it = us.iterator();
				userIds = new ArrayList<String>();
				selectedUsers = new ArrayList<User>();
				while (it.hasNext()) {
					User user = it.next();
					selectedUsers.add(user);
					userIds.add(user.getUserId());
				}
			}
			users = userMgr.searchUsers(userIds, userRealName);
			if (selectedUsers != null && selectedUsers.size() > 0) {
				getSortByChinese(selectedUsers);
			}
			if (users != null && users.size() > 0) {
				getSortByChinese(users);
			}
		}
		return "selectComUsers";
	}

	public void getSortByChinese(List<User> userList) {
		Collections.sort(userList, new Comparator<User>() {
			public int compare(User user1, User user2) {
				return Collator.getInstance(java.util.Locale.CHINA).compare(
						user1.getRealName(), user2.getRealName());
			}
		});
	}

	public String findUsers() {
		users = userMgr.searchUsers(userIds, userRealName);
		if (users != null && users.size() > 0) {
			getSortByChinese(users);
		}
		return "usersJson";
	}

	public String addUsers() {
		try {

			Role role = roleMgr.get(id);
			Set<User> us = role.getUsers();
			List<User> delUsers = new ArrayList<User>();
			if (us != null && us.size() > 0) {
				Iterator<User> it = us.iterator();
				while (it.hasNext()) {
					User user = it.next();
					if (userIds != null && userIds.size() > 0) {
						if (!userIds.contains(user.getUserId())) {
							delUsers.add(user);
						} else {
							userIds.remove(user.getUserId());
						}
					} else {
						delUsers.add(user);
					}
				}
			}

			for (User user : delUsers) {
				role.getUsers().remove(user);
				user.getRoles().remove(role);
				userMgr.update(user);
			}
			if (userIds != null && userIds.size() > 0) {
				for (String userId : userIds) {
					User user = userMgr.get(userId);
					if (!user.getRoles().contains(role)) {
						role.getUsers().add(user);
						user.getRoles().add(role);
						userMgr.update(user);
					}
				}
			}
			setResult(ActionResult.SUCCESS, "更新成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			setResult(ActionResult.FAIL, "服务器异常！");
		}
		return JSON;
	}

	protected void getChildrenDepAndUsers(Department dep) {
		List<User> users = userMgr.findByDeptId(dep.getDepId());
		if (users != null && users.size() > 0) {
			dep.setUsers(new HashSet(users));
		}
		List<Department> children = departmentMgr.getByParentId(dep.getDepId());
		if (children != null && children.size() > 0) {
			dep.setChildren(children);
			for (Department child : children) {
				getChildrenDepAndUsers(child);
			}
		}
	}

	protected Option getOptions(Department dept) {
		Option option = new Option(dept.getDepId(), dept.getDepName(), "dep");

		List<Department> children = dept.getChildren();

		List<Option> depsOP = new ArrayList<Option>();

		if (children != null) {
			for (Department depTemp : children) {
				Option op = getOptions(depTemp);
				depsOP.add(op);
			}
		}

		List<User> users = new ArrayList(dept.getUsers());

		List<Option> userOp = new ArrayList<Option>();

		if (users != null) {
			for (User user : users) {
				Option op = new Option(user.getUserId(), user.getRealName(),
						"user");
				userOp.add(op);
			}
		}
		List<Option> childrenOp = new ArrayList<Option>();

		childrenOp.addAll(depsOP);
		childrenOp.addAll(userOp);

		option.setChildren(childrenOp);

		return option;
	};

	public RoleManager getRoleMgr() {
		return roleMgr;
	}

	public void setRoleMgr(RoleManager roleMgr) {
		this.roleMgr = roleMgr;
	}

	public String getTreeNodes() {
		return treeNodes;
	}

	public void setTreeNodes(String treeNodes) {
		this.treeNodes = treeNodes;
	}

	public List<String> getUserIds() {
		return userIds;
	}

	public void setUserIds(List<String> userIds) {
		this.userIds = userIds;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public String getUserRealName() {
		return userRealName;
	}

	public void setUserRealName(String userRealName) {
		this.userRealName = userRealName;
	}

	public List<User> getSelectedUsers() {
		return selectedUsers;
	}

	public void setSelectedUsers(List<User> selectedUsers) {
		this.selectedUsers = selectedUsers;
	}

}

class Option {
	protected String id;
	protected String name;
	protected String type;
	protected List<Option> children;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<Option> getChildren() {
		return children;
	}

	public void setChildren(List<Option> children) {
		this.children = children;
	}

	public Option(String id, String name, String type) {
		super();
		this.id = id;
		this.name = name;
		this.type = type;
	}

	public Option() {

	}
}